<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82882996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\piles;

use app\common\repositories\system\PayLogRepository;
use think\facade\Db;
use app\common\dao\piles\PilesOrderDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\users\UsersRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;
/**
 * Class PilesOrderRepository
 *
 * @mixin PilesOrderDao
 */
class PilesOrderRepository extends BaseRepository
{

    public function __construct(PilesOrderDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'propertyInfo' => function ($query) {
                    $query->field('id,name');
                    $query->bind(['property_name' => 'name']);
                },
                'pilesInfo' => function ($query) {
                    $query->field('id,piles_name,sim_key');
                    $query->bind(['piles_name', 'sim_key']);
                },
            ])
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }


    public function addInfo(array $data, int $propertyId, int $userId)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $billInfo = $this->dao->create($data);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'PILES.ORDER.ADD', $data);
            ## 充电桩订单创建事件
            event('piles.order.create', [
                'billInfo' => $billInfo,
                'userId' => $userId
            ]);
            return $billInfo;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'PILES.ORDER.EDIT', $data);
            ## 充电桩订单创建事件
            event('piles.order.upgrade', [
                'billInfo' => $info,
                'userId' => $userId
            ]);
            return $this->dao->update($info['id'], $data);
        });
    }


    public function getDetail(int $id)
    {
        $data = $this->dao->search([])
            ->with([
                'propertyInfo' => function ($query) {
                    $query->field('id,name');
                    $query->bind(['property_name' => 'name']);
                },
            ])
            ->where('id', $id)
            ->find();
        return $data;
    }


    public function batchDelete(array $ids, int $userId = 0, string $remark = '')
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ], 'id,property_id,user_id,status,order_no,pay_type,actual_amount,pay_price');
        if ($list) {
            $num = 0;
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId, $remark);
                $num++;
            }
            return $num;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0, string $remark = '')
    {
        return Db::transaction(function () use ($info, $userId, $remark) {

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'PILES.ORDER.DEL', $info);
            ## 充电桩订单删除事件
            event('piles.order.delete', [
                'remark' => $remark,
                'orderInfo' => $info,
                'userId' => $userId
            ]);
            return $this->dao->delete($info['id']);
        });
    }


    public function refund($refundPrice, $orderInfo, int $userId = 0)
    {
        return Db::transaction(function () use ($refundPrice, $userId, $orderInfo) {
            if ($orderInfo['user_id'] > 0 && $refundPrice > 0) {
                if ($orderInfo['pay_type'] == 'balance') {
                    /** @var UsersRepository $usersRepository */
                    $usersRepository = app()->make(UsersRepository::class);
                    $usersRepository->balanceChange($orderInfo['user_id'], 32, $refundPrice, [
                        'note' => '充电费用退回',
                        'link_id' => $orderInfo['id']
                    ]);
                } else {
                    if ($orderInfo['pay_log_id'] > 0) {
                        /** @var PayLogRepository $payLogRepository */
                        $payLogRepository = app()->make(PayLogRepository::class);
                        $payLogRepository->refundById($orderInfo['pay_log_id'], '充电费用退回', $refundPrice);
                    }
                }

                /** @var PropertyUsersLogRepository $repository */
                $repository = app()->make(PropertyUsersLogRepository::class);
                $repository->addInfo($orderInfo['property_id'], $userId, 'PILES.ORDER.REFUND', $orderInfo);

                return $this->dao->update($orderInfo['id'], [
                    'pay_status' => 2,
                    'refund_price' => $refundPrice
                ]);
            }
        });
    }

    public function getPilesOrderNo(int $propertyId)
    {
        return 'P' . date('ymd') . rand(1111, 9999) . date('His') . $propertyId;
    }
}